package com.winit.schedule.job.tracker.clean;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.winit.schedule.core.conf.Configuration;
import com.winit.schedule.core.service.AbstractService;
import com.winit.schedule.core.utils.Clock;
import com.winit.schedule.core.utils.DateUtils;
import com.winit.schedule.job.tracker.JobTrackerContext;
import com.winit.schedule.job.tracker.conf.JobConfiguration;

public class DataCleanService extends AbstractService {

    private final Logger                   logger       = LoggerFactory.getLogger(DataCleanService.class);

    private final ScheduledExecutorService taskExecutor = Executors.newScheduledThreadPool(1);

    private JobTrackerContext              jobTrackerContext;

    public DataCleanService(JobTrackerContext jobTrackerContext){
        super("DataCleanService");
        this.jobTrackerContext = jobTrackerContext;
    }

    @Override
    protected void serviceInit(Configuration conf) throws Exception {
        super.serviceInit(conf);
    }

    @Override
    protected void serviceStart() throws Exception {
        super.serviceStart();
        Calendar c = Calendar.getInstance(Clock.getTimeZone());
        c.setTimeInMillis(Clock.getSystemTime());

        int hours = c.get(Calendar.HOUR_OF_DAY);

        if (hours > 4) {
            hours = 24 - hours + 4;
        } else {
            hours = 4 - hours;
        }

        int minute = hours * 60 - c.get(Calendar.MINUTE);

        if (minute < 0) {
            minute = 24 * 60 - minute;
        }

        // 每天凌晨4点左右执行一次日志清理工作
        taskExecutor.scheduleAtFixedRate(new LogCleanThread(), minute, 24 * 60, TimeUnit.MINUTES);

        c.add(Calendar.MINUTE, minute);
        logger.info(String.format(">>>>>>>> Daily [%s] execution log cleanup task",
            DateUtils.format(c.getTime(), "HH:mm:ss")));
    }

    @Override
    protected void serviceStop() throws Exception {
        super.serviceStop();
        taskExecutor.shutdown();
    }

    class LogCleanThread extends Thread {

        @Override
        public void run() {
            try {
                int logRetainDays = getConfig().getInt(JobConfiguration.LOG_RETAIN_DAYS,
                    JobConfiguration.DEFAULT_LOG_RETAIN_DAYS);
                Calendar c = Calendar.getInstance(Clock.getTimeZone());
                c.setTimeInMillis(Clock.getSystemTime());
                c.add(Calendar.DAY_OF_MONTH, -Math.abs(logRetainDays));
                long time = c.getTimeInMillis();

                Date date = new Date(time);
                logger.info(String.format("Clear [%s] before the log.", DateUtils.format(date)));

                jobTrackerContext.getScheduleDataManager().deleteLogByLogtime(time);
                jobTrackerContext.getScheduleDataManager().deleteRunRecordByStarttime(time);
            } catch (Exception e) {
                logger.error("log clean failure.", e);
            }

        }
    }

}
